package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.enums.UserType;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.CustomerDao;
import com.weipai.springboot.module.dao.GiftCertificateDao;
import com.weipai.springboot.module.dao.GoodsDao;
import com.weipai.springboot.module.dao.PersonalDao;
import com.weipai.springboot.module.mapper.CustomerMapper;
import com.weipai.springboot.module.mapper.ShopMapper;
import com.weipai.springboot.module.service.PersonalService;
import com.weipai.springboot.module.util.DateUtils;
import com.weipai.springboot.module.util.IdentificaCardIdUtil;
import com.weipai.springboot.module.util.SessionUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.security.util.Resources_sv;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/27 11:10
 */
@Service
public class PersonalServiceImpl implements PersonalService {

    @Autowired
    private PersonalDao personalDao;
    @Autowired
    private SessionUserUtil sessionUserUtil;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GiftCertificateDao giftCertificateDao;

    //获取用户的需求
    @Override
    public Response getDemandByCustomerId() {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        List<Map<String, Object>> demandList = personalDao.getDemandByCustomerId(customerId);
        if (demandList.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.put("demandList", demandList);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


    //添加需求
    @Override
    public Response saveDemand(Demand demand) {
        Response response = new Response();
//        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
//        demand.setCustomerId(customerId);
        demand.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
        demand.setDemandNumber(outTradeNo());
        if (personalDao.saveDemand(demand) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    /**
     * 生成订单号
     *
     * @return
     */
    public String outTradeNo() {
        Random random = new Random();
        return System.currentTimeMillis() + String.valueOf(random.nextInt(2000000000));
    }

    //获取需求分类
    @Override
    public Response getDemandCategory() {
        Response response = new Response();
        List<Map<String, Object>> list = personalDao.getDemandCategory();
        if (list.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.put("demandCategory", list);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //申请店铺
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response applyForShop(Shop shop, String customerId) {
        Response response = new Response();

        Customer customer = customerMapper.getCustomerById(customerId);
        //判断用户是否为员工, 如果员工不可以申请店铺
        if (customer.getCustomerCategoryId() == UserType.EMPLOYEE.getType()) {
            response.setCode(RetCode.REQUEST_ERROR_EMPLOYEE);
            return response;
        } else {
            //判断是否 申请过店铺, 申请过 则 删除 ---申请时为 两个页面, 第一个是 插入,第二个是更新
            Shop shop22 = shopMapper.getShopByCustomerId(customerId);
            shop.setApplicantStatus(0);
            if (shop22 != null) {
                if (shop.getShopLogo() == null) {
                    shop.setShopLogo(shop22.getShopLogo());
                }
                if (shop.getBusinessLicense() == null) {
                    shop.setBusinessLicense(shop22.getBusinessLicense());
                }
                shopMapper.deleteByPrimaryKey(shop22.getShopId());
            }
            if (personalDao.applyForShop(shop) == 1) {
                response.setCode(RetCode.SUCCESS);
                response.put("shop", shop);
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
            }
        }
        return response;
    }


    //申请店铺-------------------------------------web端
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response applyForShopWeb(Shop shop, String customerId) {
        Response response = new Response();

        Customer customer = customerMapper.getCustomerById(customerId);
        //判断用户是否为员工, 如果员工不可以申请店铺
        if (customer.getCustomerCategoryId() == UserType.EMPLOYEE.getType()) {
            response.setCode(RetCode.REQUEST_ERROR_EMPLOYEE);
            return response;
        } else {
            //判断是否 申请过店铺, 申请过 则 删除 ---申请时为 两个页面, 第一个是 插入,第二个是更新
            Shop shop22 = shopMapper.getShopByCustomerId(customerId);
            if (shop22 != null) {
                if (shop.getShopLogo() == null) {
                    shop.setShopLogo(shop22.getShopLogo());
                }
                if (shop.getBusinessLicense() == null) {
                    shop.setBusinessLicense(shop22.getBusinessLicense());
                }
                if (shop.getIdCardFront() == null) {
                    shop.setIdCardFront(shop22.getIdCardFront());
                }
                if (shop.getIdCardReverse() == null) {
                    shop.setIdCardReverse(shop22.getIdCardReverse());
                }
                shopMapper.deleteByPrimaryKey(shop22.getShopId());
            }
            shop.setApplicantStatus(0);
            if (personalDao.applyForShop(shop) == 1) {
                response.setCode(RetCode.SUCCESS);
                response.put("shop", shop);
            } else {
                response.setCode(RetCode.REQUEST_ERROR);
            }
        }
        return response;
    }


    //获取店铺分类
    @Override
    public Response getShopCategory() {
        Response response = new Response();
        List<Map<String, Object>> list = personalDao.getShopCategory();
        if (list.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.put("shopCategory", list);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //用户反馈
    @Override
    public Response customerFeedBack(String feedText) {
        Response response = new Response();
        CustomerFeedback feedback = new CustomerFeedback();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        feedback.setCustomerId(customerId);
        feedback.setFeedbackText(feedText);
        if (personalDao.saveCustomerFeedBack(feedback) == 1) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //用户的优惠券
    @Override
    public Response getCustomerGift(Integer status, Integer page, Integer size, String customerId) {
        Response response = new Response();
        Integer start = (page - 1) * size;
        List<Map<String, Object>> list = personalDao.getCustomerGift(customerId, status, start, size);

        if (list != null && list.size() > 0) {
            Integer totalNum = personalDao.getCustomerGiftAmount(customerId, status);
            PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, "");
            response.setCode(RetCode.SUCCESS);
            response.put("pageList", pageList);
        } else {
            response.setCode(RetCode.NO_DATA);
        }

        return response;
    }

    //领取优惠券
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    @Override
    public Response receiveGift(String giftId, String customerId) {
        Response response = new Response();
//        String customerId = SessionUserUtil.getUserAttr().getCustomerId();
        //验证用户是否领取过
        Integer number = personalDao.verifiCustomerGift(customerId, giftId);
        if (number > 0) {
            response.setCode(RetCode.GIFT_DATA);
            return response;
        }

        //验证礼券是否领完
        GiftCertificate gift = giftCertificateDao.getGiftCertificateById(giftId);
        if (gift.getGiftCertificateNumber() <= gift.getSoldOutNumber()) {
            response.setCode(RetCode.GIFT_NUM);
            return response;
        }

        CustomerGift customerGift = new CustomerGift();
        customerGift.setCustomerId(customerId);
        customerGift.setGiftCertificateId(giftId);
        if (personalDao.saveCustomerGift(customerGift) == 1) {
            gift.setSoldOutNumber(gift.getSoldOutNumber() + 1);
            giftCertificateDao.updateByPrimaryKey(gift);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //保存评论
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response saveEvaluate(String goodsSpec, String evaluateText, String spuNumber, Integer star,
                                 String result, Integer isAnonymity, String goodsId) {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        CustomerEvaluate evaluate = new CustomerEvaluate();
        evaluate.setCustomerId(customerId);
        evaluate.setEvaluateText(evaluateText);
        evaluate.setSpuNumber(spuNumber);
        evaluate.setEvaluateImg(result);
        evaluate.setGoodsSpec(goodsSpec);
        evaluate.setEvaluateStart(star);
        evaluate.setIsAnonymity(isAnonymity);
        if (personalDao.saveEvaluate(evaluate) == 1) {
            //通过商品id查询出此商品评价赠送的积分
            Map<String, Object> map = goodsDao.getCommentIntegralByGoodsId(goodsId);
            //保存积分记录
            saveCustomerIntegral(3, customerId, 0, Integer.parseInt(map.get("commentIntegral").toString()), goodsId);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    /**
     * 积分记录
     *
     * @param type：1表示换购商品，2表示购买商品赠送，3表示评论商品赠送
     * @param customerId：用户id
     * @param cutOff：表示商品数量
     * @param amount：表示积分
     * @param goodsId：商品id
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void saveCustomerIntegral(int type, String customerId, int cutOff, Integer amount, String goodsId) {
        CustomerIntegral customerIntegral = new CustomerIntegral();
        customerIntegral.setConsumeType(type);
        customerIntegral.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
        customerIntegral.setCustomerId(customerId);
        customerIntegral.setCutOff(cutOff);
        customerIntegral.setIntegralValue(amount);
        customerIntegral.setGoodsId(goodsId);
        customerDao.saveCustomerIntegral(customerIntegral);
    }


    //提交身份证
    @Override
    public Response identificationCard(String img, String type) {
        return IdentificaCardIdUtil.idCardOCR(img, type);
    }

    //验证身份证图片是否可用
    @Override
    public Response varIdCardImg(String shopId) {
        Response response = new Response();
        Shop shop = shopMapper.selectByPrimaryKey(shopId);

        //获得图片链接地址
        String frontImgPath = shop.getIdCardFront();
        String backImgPath = shop.getIdCardReverse();

        if (frontImgPath != null && !(frontImgPath.equals(""))) {
            //验证正面
            response = IdentificaCardIdUtil.idCardOCR(frontImgPath, "front");
        } else {
            response.setCode(RetCode.VAR_FRONT);
            return response;
        }
        if (backImgPath != null && !(backImgPath.equals(""))) {
            //验证反面
            response = IdentificaCardIdUtil.idCardOCR(frontImgPath, "back");
        } else {
            response.setCode(RetCode.VAR_BACK);
            return response;
        }
        return response;
    }

    //获取用户的积分记录
    @Override
    public Response getCustomerIntegralInfo() {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        List<Map<String, Object>> map = personalDao.getCustomerIntegralInfo(customerId);
        if (!map.isEmpty()) {
            response.setCode(RetCode.SUCCESS);
            response.setData(map);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }


}
